package cn.edu.scau.cmi.prewarning.controller;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Adulterlink;
import cn.edu.scau.cmi.ema.domain.Adultertype;
import cn.edu.scau.cmi.ema.domain.Echart;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Eventadulterlink;
import cn.edu.scau.cmi.ema.domain.Eventpunish;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodbatchfiller;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.ema.util.CmiSetUtil;
import cn.edu.scau.cmi.front.controller.FrontCmiEmaController;

@Controller
public class EchartPrewarningController extends FrontCmiEmaController {



	@RequestMapping("/frontBarEchart")
	public ModelAndView frontBarEchart() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontBarEchart.jsp");
		entityFactoryService.iniEventhazard();
		return mav;
	}
	
	@RequestMapping("/frontSimpleLineEchart")
	public ModelAndView frontSimpleLineEchart() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontSimpleLineEchart.jsp");
		return mav;
	}
	
	@RequestMapping("/frontCustomizedPieEchart")
	public ModelAndView frontCustomizedPieEchart() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontCustomizedPieEchart.jsp");
		return mav;
	}
	
	@RequestMapping("/frontBasicScatterEchart")
	public ModelAndView frontBasicScatterEchart() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("front/frontBasicScatterEchart.jsp");
		return mav;
	}
	
	@RequestMapping("/frontEchart")
	public ModelAndView frontEchart(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		
//		Integer foodtypeId = Integer.valueOf(request.getParameter("foodtypeId"));

//		mav.addObject("foodtypeName", getFoodtypeName(foodtypeId));
//		allProvinces = addressDAO.findAddressByLevel(3);//获取省级地址，可能包含国外的，需要过滤掉！！！
		//获取省级地址，可能包含国外的，需要过滤掉！！！level 3表示是省级地址，9表示地址是中国的id号。
		Set<Address> provinces = cmiAddressDAO.findAddressByLevelAndParent(3, 9);
		
		mav.addObject("provinces", provinces );
		mav.addObject("foodtypeName", "事件统计");
		mav.setViewName("front/frontEchart.jsp");
		return mav;
	}
	
	@RequestMapping("/frontTrend")
	public ModelAndView frontTrend(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		 
//		Integer foodtypeId = Integer.valueOf(request.getParameter("foodtypeId"));

//		mav.addObject("foodtypeName", getFoodtypeName(foodtypeId));
//		allProvinces = addressDAO.findAddressByLevel(3);//获取省级地址，可能包含国外的，需要过滤掉！！！
		//获取省级地址，可能包含国外的，需要过滤掉！！！level 3表示是省级地址，9表示地址是中国的id号。
		Set<Address> provinces = cmiAddressDAO.findAddressByLevelAndParent(3, 9);
		
		mav.addObject("provinces", provinces );
		mav.addObject("foodtypeName", "事件统计");
		mav.setViewName("front/frontTrend.jsp");
		return mav;
	}
	

	

	@RequestMapping("/importEvent2EchartDashBoard")
	public ModelAndView importEvent2EchartDashBoard() {
		ModelAndView mav = new ModelAndView();
//		查找echart最大的记录号作为页面的默认的起始记录
//		查找event最大的记录号作为页面的默认的终止记录
		
		Event lastEvent = cmiEventDAO.findLastEvent();
		Echart lastEchart = cmiEchartDAO.findLastEchart();
		mav.addObject("lastEchart", lastEchart);
		mav.addObject("lastEvent", lastEvent);
//		mav.setViewName("maintance/maintanceEvent2Echart.jsp");
		mav.setViewName("prewarning/importEvent2EchartDashBoard.jsp");
		return mav;
	}
	
	
	@RequestMapping("/updateEchartMainfoodtype")
	public ModelAndView updateEchartMainfoodtype(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		
		Set<Echart> echarts = echartDAO.findAllEcharts();
		int all = echarts.size();
		int yij = 1;
//		for(int i =0; i<echarts.size();i++) {
		for(Echart echart : echarts) {
			echart.getFoodtype();
			Foodtype foodtype = CmiSetUtil.getFirstInstance(foodtypeDAO.findFoodtypeByName(echart.getFoodtypename()));
			
			Foodtype mainFoodtype = getMainFoodtype(foodtype);
			
			echart.setFoodmaintype(mainFoodtype.getName());
			echartDAO.store(echart);
			echartDAO.flush();
			System.out.println(echart.getFoodname() + "的主类别是：" + echart.getFoodmaintype()+ "还有" + (all - yij));
			yij++;
			
		}
		
		return mav;
	}
	
	
	
	
	//	TODO 2021-1021-0011 需要测试，将事件汇总到echart表格中。
	@RequestMapping("/importEvent2Echart")
	public ModelAndView importEvent2Echart(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		
		int startEventId = Integer.parseInt(request.getParameter("startEventId"));
		int endEventId = Integer.parseInt(request.getParameter("endEventId"));
		
		for(int eventId =  startEventId; eventId< endEventId; eventId++) {

			Event event = eventDAO.findEventById(eventId);
//			如果eventId是空，就下一个事件的id.
			if(event == null) {
				continue;
			}
			Echart echart = new Echart();
//			如果已经导入，就不再导入。
			Set<Echart> echarts = echartDAO.findEchartByName(String.valueOf(eventId));
			if(echarts.size()>0) {
				continue;
			}
			
			echart.setEvent(event.getId());
			echart.setEventname(event.getName());
			
			echart.setSourcecountry(getAddress(event.getSourceAddress().getName(), 2).getName());
			echart.setSourceprovince(getAddress(event.getSourceAddress().getName(), 3).getName());
			echart.setSourcecity(getAddress(event.getSourceAddress().getName(), 4).getName());
			
			echart.setDiscoverycountry(getAddress(event.getSourceAddress().getName(), 2).getName());
			echart.setDiscoveryprovince(getAddress(event.getSourceAddress().getName(), 3).getName());
			echart.setDiscoverycity(getAddress(event.getSourceAddress().getName(), 4).getName());
			
			Food food = event.getFoodbatch().getFood();
			Foodtype foodtype = event.getFoodbatch().getFood().getFoodtype();
			Foodtype mainFoodtype = getMainFoodtype(foodtype);
			
			echart.setFoodtypename(foodtype.getName());
			echart.setSourceTime(event.getSourceTime());
			echart.setDiscoveryTime(event.getDiscoveryTime());
			echart.setDescription(event.getDescription());
			
			Set<Adultertype> adultertypes = event.getAdultertypesForEvent();
//			可能有多个欺诈类型。只取一个？？？
			if(adultertypes.size()>0) {
				echart.setAdultertype(CmiSetUtil.getFirstInstance(adultertypes).getName());
			}
			
			Set<Eventadulterlink> eventadulterlinks = event.getEventadulterlinksForEvent();
			String eventadulterlinksName = "";
//			可能有多个欺诈类型。只取一个？？？
			if(eventadulterlinks.size()>0) {
				for(Eventadulterlink eventadulterlink:eventadulterlinks) {
					eventadulterlinksName = eventadulterlinksName + " " + eventadulterlink.getAdulterlink().getName();
				}
			}
			echart.setAdulterlink(eventadulterlinksName);
			
			
			echart.setFoodname(food.getName());
			echart.setSubject(event.getSubject().getName());
			echart.setFoodmaintype(mainFoodtype.getName());
			Set<Foodbatchfiller> fillers = event.getFoodbatch().getFoodbatchfillersForFoodbatch();
//			如果有多个，就需要把这些filler使用
			String fillerName = "";
			if(fillers.size()>0) {
				for(Foodbatchfiller filler:fillers) {
					fillerName = fillerName + " " + filler.getFiller().getName();
				}
			}
			echart.setFoodbatchfiller(fillerName.trim());
			String punishName = "";
			
			Set<Eventpunish> eventpunishs = event.getEventpunishsForEvent();
			if(eventpunishs.size()>0) {
				for(Eventpunish eventpunish : eventpunishs) {
					punishName = punishName +  " " + eventpunish.getPunish().getName();
				}
			}
			
			echart.setPunish(punishName);
			
			try {
				echartService.saveEchart(echart);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			System.out.println("Event记录已经导入到了Echart表中" + eventId);
		}
		return mav;
	}

	
//	还要仔细思考一下
	private Foodtype getMainFoodtype(Foodtype foodtype) {
		
		
		if(foodtype.getId() != -2 &&foodtype.getParent().getId() != -2 && foodtype.getParent().getParent().getId() != -2) {
			foodtype = foodtype.getParent();
			getMainFoodtype(foodtype);
		}
		return foodtype;
	}

	//	TODO 2021-1021-0011 需要测试
//	level: 2 国家，level: 3 省， level: 4 市
	@RequestMapping("/getAddressName/{addressName}/{level}")
	public Address getAddress(@PathVariable String addressName, @PathVariable Integer level) {
		Set<Address> addresss = addressDAO.findAddressByName(addressName);
		Address address = CmiSetUtil.getLastInstance(addresss);
		while(address != null && address.getLevel() > level) {
			address = address.getParent();
		}
		
		if(address != null) {
			System.out.println(addressName + "的上一级地址是：" + address.getName());
		}else {
			System.out.println(addressName + "在数据库中没有找到");
		}
		
		return address;
	}
}